package com.zzg.demo.laboratory.threadpool;

import java.util.concurrent.*;

public class TestThreadPoolNoShutdown {
    private static ThreadPoolExecutor getThreadPoolExecutor(int corePoolSize, int maximumPoolSize) {
        return new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                0L,
                TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<>(20),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy() // 当任务被拒绝时在调用者线程中运行任务
        );
    }

    public static void print(){
        System.out.println("Hello World：" + Thread.currentThread().getName());
    }
    
    public static void main(String[] args) {
        int max = 10;
        for(int i = 0; i < max; i++){
            // 每次都new一个新线程池
            ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor(10, 15);
            for(int j = 0; j < 5; j++){
                threadPoolExecutor.execute(TestThreadPoolNoShutdown::print);
            }
            // 如果不shutdown，那么这个线程池会一直在内存中驻留，线程池中的核心线程永远在wait状态，导致内存泄露
            if(i != 5){
                threadPoolExecutor.shutdown();
            }
        }
        System.out.println("end");
    }
}
